package com.mazsn.annotate;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import com.mazsn.bean.User;

/**
 * 方法参数的注解解析器
 * @author mazhongshan
 *
 */
public class CurrentUserMethodArgumentResolver implements  HandlerMethodArgumentResolver {

	@Override
	public Object resolveArgument(MethodParameter arg0, ModelAndViewContainer arg1, NativeWebRequest webRequest,
			WebDataBinderFactory arg3) throws Exception {
		User user = (User) webRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST);
		if (user != null) {
            return user;
        }else if(user==null){
        	//未写登录 仅为测试用
        	return user = new User();
        }
        throw new MissingServletRequestPartException("currentUser");
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(User.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
	}

}
